from core.tools.custom_requests import CustomRequests
from core.tools.get_datetime import GetDateTime


class Oauth(CustomRequests):
    def __init__(self, client):
        self.client = client

    def fetch_oauth_token(self, code):
        """获取 access_token

        :param code: 授权完成跳转回来后 URL 中的 code 参数
        :return: JSON 数据包
        """
        url = "https://openapi.alipay.com/gateway.do"
        params = {
            'app_id': self.client.appid,
            'method': "alipay.system.oauth.token",
            'charset': self.client.charset,
            'sign_type': self.client.sign_type,
            'grant_type': 'authorization_code',
            "code": code,
            "timestamp": GetDateTime.format_datetime("%Y-%m-%d %H:%M:%S"),
            "sign_type": self.client.sign_type,
            "charset": self.client.charset,
            "version": self.client.version,
        }
        sign_content = self.client.get_sign_content(params)
        sign = self.client.sign_with_rsa2(sign_content)
        params["sign"] = sign
        response = self.get(url, params=params)
        return response
